/*
 This file is part of jRecon.

 jRecon is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 jRecon is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with jRecon.  If not, see <http://www.gnu.org/licenses/>.
 */
//TODO add option to not traceroute.
//TODO add options to scan only pingable destination
package fr.sapk.jrecon;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Antoine
 */
public class UIFrameHome extends javax.swing.JFrame {

    final static Charset ENCODING = StandardCharsets.UTF_8;

    /**
     * Creates new form NewJFrame
     */
    public UIFrameHome() {
        initComponents();
        setIconImage(Tool.loadImageIcon("/img/icon.png").getImage());
        setResizable(false);
        //setName("jRecon");
        setTitle("jRecon");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane = new javax.swing.JTabbedPane();
        jPanelAnalyse = new javax.swing.JPanel();
        ButtonGO = new javax.swing.JButton();
        InputTarget = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        CheckBoxPort = new javax.swing.JCheckBox();
        InputPort = new javax.swing.JTextField();
        CheckBoxLimit = new javax.swing.JCheckBox();
        InputLimit = new javax.swing.JTextField();
        CheckBoxDNS = new javax.swing.JCheckBox();
        InputName = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        TextAreaEstimation = new javax.swing.JTextArea();
        PanelResults = new javax.swing.JPanel();
        ButtonShowGraph = new javax.swing.JButton();
        ButtonExport = new javax.swing.JButton();
        ButtonSupprimer = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        InfoScanPanel = new javax.swing.JTextPane();
        ComboBoxResult = new javax.swing.JComboBox();
        ShowOrphin = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        ButtonResetDB = new javax.swing.JButton();
        ButtonImport = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        bProgressBar = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTabbedPane.setAlignmentX(0.0F);
        jTabbedPane.setAlignmentY(0.0F);
        jTabbedPane.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jTabbedPane.setMinimumSize(new java.awt.Dimension(506, 200));
        jTabbedPane.setPreferredSize(new java.awt.Dimension(506, 300));

        ButtonGO.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        ButtonGO.setText("GO !");
        ButtonGO.setToolTipText("");
        ButtonGO.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonGOActionPerformed(evt);
            }
        });

        InputTarget.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        InputTarget.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                InputTargetKeyReleased(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("IP Range \\ Hostname :");

        CheckBoxPort.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CheckBoxPort.setText("Port scan");
        CheckBoxPort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckBoxPortActionPerformed(evt);
            }
        });

        InputPort.setEditable(false);
        InputPort.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        InputPort.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                InputPortKeyReleased(evt);
            }
        });

        CheckBoxLimit.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CheckBoxLimit.setText("Limitation");
        CheckBoxLimit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckBoxLimitActionPerformed(evt);
            }
        });

        InputLimit.setEditable(false);
        InputLimit.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        InputLimit.setText("10");
        InputLimit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                InputLimitActionPerformed(evt);
            }
        });
        InputLimit.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                InputLimitKeyReleased(evt);
            }
        });

        CheckBoxDNS.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CheckBoxDNS.setText("DNS Resolution");
        CheckBoxDNS.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckBoxDNSActionPerformed(evt);
            }
        });

        InputName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        InputName.setToolTipText("Nom de l'analyse");

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(null, "Estimation", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("5x5 Pixel", 0, 14)))); // NOI18N

        TextAreaEstimation.setEditable(false);
        TextAreaEstimation.setBackground(new java.awt.Color(111, 111, 111));
        TextAreaEstimation.setColumns(20);
        TextAreaEstimation.setFont(new java.awt.Font("Miriam Fixed", 0, 12)); // NOI18N
        TextAreaEstimation.setLineWrap(true);
        TextAreaEstimation.setRows(5);
        TextAreaEstimation.setText("Config. invalid");
        TextAreaEstimation.setWrapStyleWord(true);
        TextAreaEstimation.setAutoscrolls(false);
        TextAreaEstimation.setFocusable(false);
        jScrollPane2.setViewportView(TextAreaEstimation);

        javax.swing.GroupLayout jPanelAnalyseLayout = new javax.swing.GroupLayout(jPanelAnalyse);
        jPanelAnalyse.setLayout(jPanelAnalyseLayout);
        jPanelAnalyseLayout.setHorizontalGroup(
            jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelAnalyseLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(InputName)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelAnalyseLayout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(InputTarget))
                    .addGroup(jPanelAnalyseLayout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelAnalyseLayout.createSequentialGroup()
                                .addComponent(CheckBoxDNS)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelAnalyseLayout.createSequentialGroup()
                                .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(CheckBoxPort)
                                    .addComponent(CheckBoxLimit))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(InputPort, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                                    .addComponent(InputLimit)))
                            .addComponent(ButtonGO, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(10, 10, 10))
        );
        jPanelAnalyseLayout.setVerticalGroup(
            jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelAnalyseLayout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(InputName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(InputTarget, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanelAnalyseLayout.createSequentialGroup()
                        .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(CheckBoxPort)
                            .addComponent(InputPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanelAnalyseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(CheckBoxLimit)
                            .addComponent(InputLimit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CheckBoxDNS)
                        .addGap(18, 18, 18)
                        .addComponent(ButtonGO, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2))
                .addGap(10, 10, 10))
        );

        jTabbedPane.addTab("Analyse", jPanelAnalyse);

        PanelResults.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        PanelResults.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                PanelResultsComponentShown(evt);
            }
        });

        ButtonShowGraph.setText("Show Graph");
        ButtonShowGraph.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonShowGraphActionPerformed(evt);
            }
        });

        ButtonExport.setText("Exporter");
        ButtonExport.setToolTipText("");
        ButtonExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonExportActionPerformed(evt);
            }
        });

        ButtonSupprimer.setText("Supprimer");
        ButtonSupprimer.setToolTipText("");
        ButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonSupprimerActionPerformed(evt);
            }
        });

        InfoScanPanel.setEditable(false);
        InfoScanPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Infos", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
        jScrollPane1.setViewportView(InfoScanPanel);

        ComboBoxResult.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        ComboBoxResult.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ComboBoxResultActionPerformed(evt);
            }
        });

        ShowOrphin.setText("Afficher orphelins");
        ShowOrphin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShowOrphinActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PanelResultsLayout = new javax.swing.GroupLayout(PanelResults);
        PanelResults.setLayout(PanelResultsLayout);
        PanelResultsLayout.setHorizontalGroup(
            PanelResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelResultsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PanelResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ComboBoxResult, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(PanelResultsLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(PanelResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(ButtonSupprimer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ButtonShowGraph, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                            .addComponent(ButtonExport, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ShowOrphin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        PanelResultsLayout.setVerticalGroup(
            PanelResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelResultsLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ComboBoxResult, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PanelResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PanelResultsLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(ButtonShowGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ButtonExport, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(12, 12, 12)
                        .addComponent(ButtonSupprimer, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                        .addComponent(ShowOrphin))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );

        jTabbedPane.addTab("Results", PanelResults);

        ButtonResetDB.setText("Reset DB");
        ButtonResetDB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonResetDBActionPerformed(evt);
            }
        });

        ButtonImport.setText("Import");
        ButtonImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonImportActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(286, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ButtonResetDB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ButtonImport, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ButtonResetDB, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(ButtonImport, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(131, Short.MAX_VALUE))
        );

        jTabbedPane.addTab("Config", jPanel2);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 528, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 241, Short.MAX_VALUE)
        );

        jTabbedPane.addTab("Logs", jPanel3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(bProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
            .addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CheckBoxPortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckBoxPortActionPerformed
        if (CheckBoxPort.isSelected()) {
            InputPort.setEditable(true);
        } else {
            InputPort.setEditable(false);
        }

        Estimate();
    }//GEN-LAST:event_CheckBoxPortActionPerformed

    private void CheckBoxLimitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckBoxLimitActionPerformed
        if (CheckBoxLimit.isSelected()) {
            InputLimit.setEditable(true);
        } else {
            InputLimit.setEditable(false);
        }

        Estimate();
    }//GEN-LAST:event_CheckBoxLimitActionPerformed

    private void ButtonGOActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonGOActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ButtonGOActionPerformed

    private void InputTargetKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_InputTargetKeyReleased
        Estimate();
    }//GEN-LAST:event_InputTargetKeyReleased

    private void InputPortKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_InputPortKeyReleased
        Estimate();
    }//GEN-LAST:event_InputPortKeyReleased

    private void InputLimitKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_InputLimitKeyReleased
        Estimate();
    }//GEN-LAST:event_InputLimitKeyReleased

    private void CheckBoxDNSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckBoxDNSActionPerformed
        Estimate();
    }//GEN-LAST:event_CheckBoxDNSActionPerformed

    private void InputLimitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InputLimitActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_InputLimitActionPerformed

    private void ButtonShowGraphActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonShowGraphActionPerformed

        String selected = ComboBoxResult.getSelectedItem().toString();
        //TODO
        try {
            buildXMLMap(selected.split("\\)")[0]);
            try {
                // TODO add your handling code here:
                new Thread(new UIFrameMap(Tool.get_root_folder()+"data/map.xml")).start();
            } catch (Throwable ex) {
                Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (IOException | SQLException ex) {
            Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_ButtonShowGraphActionPerformed

    private void ButtonResetDBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonResetDBActionPerformed
        DB db = new DB();
        db.reset();
    }//GEN-LAST:event_ButtonResetDBActionPerformed

    private void ButtonExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonExportActionPerformed
        try {

            String selected = ComboBoxResult.getSelectedItem().toString();
            //TODO
            ResultSet analyse = DB.query("SELECT * FROM analyse WHERE id_analyse=" + selected.split("\\)")[0]);
            String id = analyse.getString("id_analyse");
            //query.
            File file;
            do {
                JFileChooser choix = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "jRecon File", "jrc");
                choix.setFileFilter(filter);
//                choix.setDialogType(JFileChooser.SAVE_DIALOG);
                choix.removeChoosableFileFilter(choix.getAcceptAllFileFilter());
                int retour = choix.showSaveDialog(this);
                if (retour == JFileChooser.APPROVE_OPTION) {
                    System.out.println(choix.getSelectedFile().getAbsolutePath());
                    file = choix.getSelectedFile();
                    System.out.println(file.getName());
                    if (!(file.getName().endsWith("jrc"))) {
                        file = new File(choix.getSelectedFile().getAbsolutePath() + ".jrc");
                    }
                } else {
                    System.out.println("Aucun fichier selectionné");
                    return;
                }
                //File file = new File("data/export/export-" + URLEncoder.encode(analyse.getString("name").split("#")[0]) + "-" + analyse.getString("timestamp") + ".sql");
                if (file.exists()) {
                    System.out.println("Fichier déjà existant");
                }
            } while (file.exists());

            System.out.println(file.getAbsolutePath());
            file.createNewFile();
            try (FileWriter writer = new FileWriter(file)) {
                writer.write("/* export : " + analyse.getString("id_analyse") + " */" + "\n" + "\n" + "\n");

                writer.write("INSERT INTO analyse  ('id_analyse', 'state', 'name', 'target', 'port', 'limit', 'checkdns', 'timestamp', 'ended_at') VALUES ($$ID_ANALYSE$$, 'Imported', '" + analyse.getString("name") + "', '" + analyse.getString("target") + "', '" + analyse.getString("port") + "', '" + analyse.getString("limit") + "', '" + analyse.getString("checkdns") + "', '" + analyse.getString("timestamp") + "', '" + analyse.getString("ended_at") + "') " + "\n");

                ResultSet host = DB.query("SELECT * FROM host WHERE id_analyse=" + id);
                while (host.next()) {
//"INSERT INTO host ('id_analyse', 'ip', 'hostname', 'tcp', 'udp', 'at') VALUES (" + id + ", '" + ip + "', '" + hostname + "', '[]', '[]', '" + timestamp + "') "
                    writer.write("INSERT INTO host  ('id_analyse', 'ip', 'hostname', 'tcp', 'udp', 'at') VALUES ($$ID_ANALYSE$$, '" + host.getString("ip") + "', '" + host.getString("hostname") + "', '" + host.getString("tcp") + "', '" + host.getString("udp") + "', '" + host.getString("at") + "') " + "\n");
                }
                writer.write("\n" + "\n");
                //host.close();
                ResultSet route = DB.query("SELECT * FROM route WHERE id_analyse=" + id);
                while (route.next()) {
//"INSERT INTO host ('id_analyse', 'ip', 'hostname', 'tcp', 'udp', 'at') VALUES (" + id + ", '" + ip + "', '" + hostname + "', '[]', '[]', '" + timestamp + "') "
                    writer.write("INSERT INTO route  ('id_analyse', 'uuid', 'hop', 'from', 'to', 'at') VALUES ($$ID_ANALYSE$$, '" + route.getString("uuid") + "', '" + route.getString("hop") + "', '" + route.getString("from") + "', '" + route.getString("to") + "', '" + route.getString("at") + "') " + "\n");

                }
                writer.flush();
            }

        } catch (SQLException | IOException ex) {
            Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_ButtonExportActionPerformed

    private void ButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonSupprimerActionPerformed

        String selected = ComboBoxResult.getSelectedItem().toString();
        try {
            DB.exec("DELETE FROM route WHERE id_analyse=" + selected.split("\\)")[0]);
            DB.exec("DELETE FROM host WHERE id_analyse=" + selected.split("\\)")[0]);
            DB.exec("DELETE FROM analyse WHERE id_analyse=" + selected.split("\\)")[0]);
            PanelResultsComponentShown(null);
        } catch (SQLException ex) {
            Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_ButtonSupprimerActionPerformed

    private void PanelResultsComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_PanelResultsComponentShown
        System.out.println("PanelResultsComponentShown()");
        try {
            ResultSet analyse = DB.query("SELECT * FROM analyse");
            List<String> names = new ArrayList<>();
            while (analyse.next()) {
                names.add(analyse.getString("id_analyse") + ") " + analyse.getString("name"));
                //jComboBox1.add(analyse.getString("name"), null);
                //
                //jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
                //jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(es));
            }
            ComboBoxResult.setModel(new javax.swing.DefaultComboBoxModel(names.toArray()));
        } catch (SQLException ex) {
            Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
        }
        ComboBoxResultActionPerformed(null);
    }//GEN-LAST:event_PanelResultsComponentShown

    private void ComboBoxResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ComboBoxResultActionPerformed
        //System.out.println(evt.paramString());             
        //TODO clean null detection (no error)
        InfoScanPanel.setText("\n");
        String selected = ComboBoxResult.getSelectedItem().toString();

        try {
            System.out.println("SELECT * FROM analyse WHERE id_analyse=" + selected.split("\\)")[0]);
            ResultSet analyse = DB.query("SELECT * FROM analyse WHERE id_analyse=" + selected.split("\\)")[0]);
            InfoScanPanel.setText("\n"
                    + "State : " + analyse.getString("state") + "\n"
                    + "Started at : " + analyse.getDate("timestamp").toLocaleString() + "\n"
                    + "Ended at : " + analyse.getDate("ended_at").toLocaleString() + "\n"
                    + "Target : " + analyse.getString("target") + "\n"
                    + "Port : " + analyse.getString("port") + "\n"
            );
        } catch (SQLException ex) {
            Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_ComboBoxResultActionPerformed

    private void ButtonImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonImportActionPerformed
        //TODO show selection box import data
        JFileChooser choix = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "jRecon File", "jrc");
        choix.setFileFilter(filter);
        choix.removeChoosableFileFilter(choix.getAcceptAllFileFilter());
        int retour = choix.showOpenDialog(this);
        if (retour == JFileChooser.APPROVE_OPTION) {
            System.out.println(choix.getSelectedFile().getAbsolutePath());
            ResultSet result;
            try {
                result = DB.query("SELECT count(*) AS count FROM analyse");
                int id_analyse = result.getInt("count") + 1;
                System.out.println(id_analyse);
                List<String> lines = Files.readAllLines(Paths.get(choix.getSelectedFile().getAbsolutePath()), ENCODING);
                for (String l : lines) {
                    //System.out.println(l);
                    //TODO replace id_analyse in file 
                    if (l.startsWith("INSERT INTO")) {
                        System.out.println(l.replace("$$ID_ANALYSE$$", "" + id_analyse));
                        DB.addQueue(l.replace("$$ID_ANALYSE$$", "" + id_analyse));
                    }
                }
                DB.execQueue();
            } catch (IOException | SQLException ex) {
                Logger.getLogger(UIFrameHome.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {

        }
    }//GEN-LAST:event_ButtonImportActionPerformed

    private void ShowOrphinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShowOrphinActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ShowOrphinActionPerformed

    private void Estimate() {
        //TODO check validity
        /*
         System.out.println(InputName.getText());
         System.out.println(InputLimit.getText());
         System.out.println(InputPort.getText());
         System.out.println(InputTarget.getText());
         System.out.println(Tool.is_network(InputTarget.getText()));
         System.out.println(Tool.is_hostname(InputTarget.getText()));
         */
        /*
         System.out.println(Integer.parseInt(InputTarget.getText().split("/")[1]));
         System.out.println(32 - Integer.parseInt(InputTarget.getText().split("/")[1]));
         System.out.println(Math.pow(2,32 - Integer.parseInt(InputTarget.getText().split("/")[1])));
         */
        if (Tool.is_network(InputTarget.getText()) || Tool.is_hostname(InputTarget.getText())) {
            double requests = 0;
            if (Tool.is_network(InputTarget.getText())) {
                //On compte les ip réseau et broadcast au cas d'une séparation simple des recherches.
                requests += Math.pow(2, 32 - Integer.parseInt(InputTarget.getText().split("/")[1]));
            } else {
                requests += 1;
            }

            requests = (requests <= 0) ? 1 : requests;
            double multi = 0;
            if (CheckBoxPort.isSelected() && InputPort.getText().split("-").length == 2) {
                //TODO check validity of range
                multi += (Integer.parseInt(InputPort.getText().split("-")[1]) - Integer.parseInt(InputPort.getText().split("-")[0]) + 1);
            }
            if (CheckBoxDNS.isSelected()) {
                multi += 1;
            }

            //System.out.println(multi);
            //request étati multiplié par 10 pour les traceroute (moyenne)
            requests = 750 * requests + (requests) * multi;

            if (CheckBoxLimit.isSelected() && InputLimit.getText().length() > 0 && Double.parseDouble(InputLimit.getText()) > 0) {
                multi = 1 / (Double.parseDouble(InputLimit.getText()));
                //TODO implement multitreading request
            } else {
                multi = 0.1;
            }

            String time = String.format("%dh%02dm%02ds", (int) (requests * multi) / 3600, ((int) (requests * multi) % 3600) / 60, ((int) (requests * multi) % 60));
            //System.out.println(requests);
            TextAreaEstimation.setText("\n\n"
                    + "Number of request : " + Compact(requests) + "Req\n"
                    + "\n"
                    + "Space required    : " + Compact(requests * 12) + "B\n"
                    + "\n"
                    + "Estimated time : " + time);
        } else {
            TextAreaEstimation.setText("\n\n"
                    + "Config. invalid");
        }
    }

    private String Compact(double n) {
        char c = ' ';
        if (n > 10000) {
            n = n / 1000;
            c = 'K';
        }
        if (n > 10000) {
            n = n / 1000;
            c = 'M';
        }
        if (n > 10000) {
            n = n / 1000;
            c = 'G';
        }
        return (int) n + " " + c;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        /*
         try {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
         if ("Nimbus".equals(info.getName())) {
         javax.swing.UIManager.setLookAndFeel(info.getClassName());
         break;
         }
         }
         } catch (ClassNotFoundException ex) {
         java.util.logging.Logger.getLogger(UIFrameHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(UIFrameHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(UIFrameHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(UIFrameHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
         */
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UIFrameHome().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonExport;
    public javax.swing.JButton ButtonGO;
    private javax.swing.JButton ButtonImport;
    private javax.swing.JButton ButtonResetDB;
    private javax.swing.JButton ButtonShowGraph;
    private javax.swing.JButton ButtonSupprimer;
    private javax.swing.JCheckBox CheckBoxDNS;
    private javax.swing.JCheckBox CheckBoxLimit;
    private javax.swing.JCheckBox CheckBoxPort;
    private javax.swing.JComboBox ComboBoxResult;
    private javax.swing.JTextPane InfoScanPanel;
    private javax.swing.JTextField InputLimit;
    private javax.swing.JTextField InputName;
    private javax.swing.JTextField InputPort;
    private javax.swing.JTextField InputTarget;
    private javax.swing.JPanel PanelResults;
    private javax.swing.JCheckBox ShowOrphin;
    private javax.swing.JTextArea TextAreaEstimation;
    public javax.swing.JProgressBar bProgressBar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanelAnalyse;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane;
    // End of variables declaration//GEN-END:variables

    void disableAll() {
        setAll(false);
    }

    void enableAll() {
        setAll(true);
    }

    void buildXMLMap(String id_analyse) throws IOException, SQLException {
        ArrayList[] data = Tool.getData(id_analyse, ShowOrphin.isSelected() );
        String xml = Tool.buildXML(data[0], data[1]);
        Tool.writetoFile(Tool.get_root_folder()+"data/map.xml", xml);

    }

    void setAll(boolean state) {
        ButtonGO.setEnabled(state);
        CheckBoxDNS.setEnabled(state);
        CheckBoxLimit.setEnabled(state);
        CheckBoxPort.setEnabled(state);
        InputLimit.setEnabled(state);
        InputName.setEnabled(state);
        InputPort.setEnabled(state);
        InputTarget.setEnabled(state);
        TextAreaEstimation.setEnabled(state);
    }

    boolean config_is_valid() {
        if (InputPort.getText().matches("^[0-9]+$")) {
            InputPort.setText(InputPort.getText() + "-" + InputPort.getText());
        }
        Estimate();
        return !TextAreaEstimation.getText().contains("Config. invalid");
    }

    String[] get_config() {
        return new String[]{
            InputName.getText(),
            InputTarget.getText().toLowerCase(),
            ((CheckBoxPort.isSelected()) ? InputPort.getText() : null),
            ((CheckBoxLimit.isSelected()) ? InputLimit.getText() : "10"),
            ((CheckBoxDNS.isSelected()) ? "true" : "false")
        };
    }

}
